﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace XiaofangExamFramework
{
    public class ClipboardHelper
    {
        private const int WM_COPY = 0x0301;

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

        public static void CopySelectedText()
        {
            IntPtr handle = GetBrowserWindowHandle(); // 获取浏览器窗口句柄

            if (handle != IntPtr.Zero)
            {
                SendMessage(handle, WM_COPY, IntPtr.Zero, IntPtr.Zero); // 发送复制消息
            }
        }

        private static IntPtr GetBrowserWindowHandle()
        {
            // 根据自己使用的浏览器类型选择相应的窗口类名
            string browserClassName = "Chrome_WidgetWin_1"; // Google Chrome  / MS Edge

            IntPtr handle = IntPtr.Zero;
            
            // 遍历当前活动的窗口，找到匹配的浏览器窗口句柄
            IntPtr currentHandle = IntPtr.Zero;
            do
            {
                currentHandle = NativeMethods.FindWindowEx(IntPtr.Zero, currentHandle, browserClassName, null);
                if (currentHandle != IntPtr.Zero && NativeMethods.IsWindowVisible(currentHandle))
                {
                    handle = currentHandle;
                    break;
                }
            } while (currentHandle != IntPtr.Zero);

            Debug.WriteLine($"window handle=>" + handle.ToString());
            return handle;
        }

        private static class NativeMethods
        {
            [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
            public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

            [DllImport("user32.dll", CharSet = CharSet.Auto)]
            public static extern bool IsWindowVisible(IntPtr hWnd);
        }
    }
}
